package PerlBot::Plugin::Social;
use strict;
use warnings;
use base 'Class::Component::Plugin';
use DateTime;
use Encode qw/encode decode/;
use URI;
use Net::Twitter;
use Me2day;
use Data::Validate::URI qw(is_uri);
use Net::Delicious;
use Web::Scraper;

sub fork : Hook('fork') {
    my ($self, $c, $args) = @_;

    return unless $self->config->{delicious};

    my $del = Net::Delicious->new({
	user => $self->config->{delicious}->{user},
	pswd => $self->config->{delicious}->{pswd},
				  });

    my $target = $args->{action} && $args->{action} eq 'privmsg' ? $args->{where} : $args->{who};
    
    my ($uri, $desc) = split /\s/, $args->{desc};
    
    unless(is_uri($uri)) {
	return $args->{irc}->yield( $args->{action} => $target => $args->{who} .":". "URL!!!!" );
    }

    my $title;

    unless ($desc) {
	my $html = scraper {
	    process 'title', title => 'TEXT';
	}->scrape(URI->new($uri));
	$title = $html->{title};
    }
    my $res = $del->add_post({
	url => $uri,
	description => ($desc || $title),
			     });
    
    if ($res) {
	$args->{irc}->yield( $args->{action} => $target => $args->{who}.":". "Bookmarked ".$args->{desc} );
    }
    
}

sub twitter_post : Hook('twitter') {
    my ($self, $c, $args) = @_;

    return unless $self->config->{twitter};

    my $twit = Net::Twitter->new(
	username => $self->config->{twitter}->{username},
	password => $self->config->{twitter}->{password},
	source   => $self->config->{twitter}->{source},
	);

    $twit->update($args->{who}. " : ". $args->{desc});
    
    my $target = $args->{action} && $args->{action} eq 'privmsg' ? $args->{where} : $args->{who};
    $args->{irc}->yield( $args->{action} => $target => "Twittered! http://twitter.com/".$self->config->{twitter}->{username} );
}

sub me2day_post : Hook('me2day') {
    my ($self, $c, $args) = @_;

    return unless $self->config->{me2day};

    my $me2day = Me2day->new(
	username => $self->config->{me2day}->{username},
	user_key => $self->config->{me2day}->{user_key},
	app_key  => $self->config->{me2day}->{app_key},
	);
    my $res;
    if ($args->{desc} && $args->{desc} =~ /@\:/) {
	my ($post, $tags) = split /@\:/, $args->{desc}; #/;
	$tags .= " me2irc";
	$res = $me2day->create_post( body => $args->{who}." : ".$post, tags => $tags );
    } else {
	$res = $me2day->create_post( body => $args->{who}." : ".$args->{desc}, tags => "me2irc");
    }

    if ($res->status_line =~ /200/) {
	my ($permalink) = $res->content =~ /<permalink>(.+)<\/permalink>/;
	my $target = $args->{action} && $args->{action} eq 'privmsg' ? $args->{where} : $args->{who};
	$args->{irc}->yield( privmsg => $args->{where} => $args->{who}." : "." Me2day Posted! ".$permalink );
	return;
    }
}

1;
